package com.caiyi.financial.nirvana.sms;

import com.caiyi.financial.nirvana.sms.cmpp20.CMPPStreamDecoder;
import com.caiyi.financial.nirvana.sms.cmpp20.CMPPStreamEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.junit.Test;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * CMPP测试客户端
 */
public class CMPPClient {
    private Channel channel;

    @Test
    public void testClient() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).
                    channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress("123.56.49.62", 8086))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 长度解码器
                            pipeline.addLast("length field decoder", new LengthFieldBasedFrameDecoder(4 * 1024, 0, 4, -4, 0));

                            pipeline.addLast("decoder", new CMPPStreamDecoder());
                            pipeline.addLast("encoder", new CMPPStreamEncoder());

                            // 空闲事件将发送UP事件，读空闲事件触发时间设置为心跳触发时间的两倍，因此一旦触发读空闲，则说明链路有问题，需要重新连接
                            pipeline.addLast("idleCheck", new IdleStateHandler(60 * 2, 60,
                                    -1, TimeUnit.SECONDS));
                            ch.pipeline().addLast(new CMPPClientHandler());
                        }
                    });

            channel = b.connect().sync().channel();


            channel.closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}
